#!/usr/bin/env ruby -wKU
#encoding: utf-8

module DB_VTB
    
  require 'active_record'
  require 'backend/data/db_impl'
  require 'backend/data/user'
  require 'backend/data/interest'
  require 'backend/data/notify'
  require 'backend/notification_mail/notification_mail'
  
  class DataProcessor
    
    def initialize crawler
      # puts 'initialize DataProcessor'
      crawler.add_observer self
    end
    
    def update items
      # puts "#{items.length} items found"
      users = DB_VTB::User.all
      # puts users.length
      users.each { |user|
        
        # puts user.id.to_s + ", " + user.email + ", " + user.name + ", " + user.password
        
        interests = user.interests
        
        user_result = []
        
        interests.each { |i|
          value = i.value
          # puts "value is #{value}"
          results = []
          items.each { |item|
            # puts "item title is " + item['title']
            if item['title'].include? value
              url = item['href']
              yesterday = Time.now - 24 * 60 * 60
              notifies = i.notifies.where("url = ? and time > ?", url, yesterday)
              # notifies.each { |n|
                # puts n.id.to_s + ", " + n.iid.to_s + ", " + n.url + ", " + n.time
              # }
              # puts '----------------------------------------------------'
              # notifies = Notify.where("url NOT IN (?)", items)
              if notifies.nil? || notifies.length == 0
                # puts "add into results"
                results << item
              end
            end
          }
          
          unless results.length == 0
            do_transaction i.id, results
            user_result << results
          end
        }
        
        unless user_result.length == 0
          # puts 'start to send a mail'
          send_mail user.email, user_result
        end
      }
    end
    
    private
    
    # FIXME: use buck insertion instead
    def do_transaction iid, results
      begin
        ActiveRecord::Base.transaction {
          results.each { |r|
            n = Notify.create(iid: iid, url: r['href'], time: Time.now)
            n.save!
          }
        }
      rescue ActiveRecord::RecordInvalid => invalid
        puts "Error: #{invalid.class}, #{invalid.message}"
      end
    end
    
    def send_mail email, results
      Thread.new {
        # puts 'create thread to send mail'
        # start_time = Time.now
        mail = Mail_VTB::NotificationMail.notification email, results
        mail.deliver
        # elapsed = Time.now - start_time
        # puts "take #{elapsed} to send a mail"
      }
    end
    
  end
  
  if __FILE__ == $0
    require 'backend/crawler/crawler'
    crawler = Crawler::WebCrawler.new
    
    dp = DB_VTB::DataProcessor.new crawler
    
    # crawler.add_observer dp
    
    thread = crawler.crawl
    thread.join
    
  end
  
end